package cn.itcast.order.service;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author danDong
 * @date 2025-02-11 17:20:34
 */
public class CreateClass {
    public static void main(String[] args) throws SQLException {
        // 1.连接数据源
        Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.75.129:3306/hm-item", "danhong", "123456");

        // 2.构造查出要生成实体的表sql
        PreparedStatement stmt = connection.prepareStatement("select table_name from information_schema.tables where table_schema = 'hm-item'");
        ResultSet rs = stmt.executeQuery();

        List<String> tableNames = new ArrayList<>();
        while (rs.next()) {
            tableNames.add(rs.getString("table_name"));
        }

        // 3.遍历表名，生成实体类
        for (String tableName : tableNames) {
            generateEntity(tableName);
        }
    }

    public static void generateEntity(String tableName){
        AutoGenerator mpg = new AutoGenerator();
        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        System.out.println(projectPath);
        //生成路径
        gc.setOutputDir(projectPath + "/user-service/src/main/java/cn/itcast/user");
        gc.setOpen(false);
        //第二次生成会把第一次生成的覆盖掉
        gc.setFileOverride(true);
        //生成resultMap
        gc.setBaseResultMap(true);
        mpg.setGlobalConfig(gc);

        // 2、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.75.129:3306/hm-item");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("danhong");
        dsc.setPassword("123456");
        // 设置数据库类型为MYSQL
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 3、包配置
        PackageConfig pc = new PackageConfig();
        // todo 模块名称即包名 建议是表名的全小写字符串
        pc.setModuleName("entity");
        mpg.setPackageInfo(pc);

        // 4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        // 使用lombok
        strategy.setEntityLombokModel(true);
        // todo 逆向工程使用的表   如果要生成多个,这里可以传入String[]
        strategy.setInclude(tableName);
        mpg.setStrategy(strategy);

        // 5、执行
        mpg.execute();
    }

}
